package com.kaver.sso.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kaver.sso.config.PropertiesConfig;
import com.kaver.sso.def.resp.User;
import com.kaver.sso.helper.SsoHelper;
import com.kaver.sso.helper.SsoUserHolder;

/**
 * 权限拦截器
 * 
 * @author roc
 */
public class RightInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	SsoHelper ssoHelper;
	@Autowired
	PropertiesConfig propertiesConfig;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        String servletPath = req.getServletPath();
        //权限校验
        User user = SsoUserHolder.get();
        if (user != null) {
        	int right = ssoHelper.checkRight(user.getUserId(), servletPath);
        	if (right == 1) {
        		return super.preHandle(request, response, handler);
        	} else if (right == 0) {
        		resp.setContentType("application/json;charset=utf-8");
                resp.getWriter().println(propertiesConfig.getSsoNoRightReturn());
                return false;
        	}
        }
		return super.preHandle(request, response, handler);
	}
	
	
}
